<template>
  <div style="font-size: 14px">
    <div style="background-color: #fafbfd;padding: 15px;margin-bottom: 15px;">
      筛选
    </div>
    <div style="padding: 0 15px;">
      <el-form ref="searchForm" :model="filters" label-suffix=":" :size="'medium'"
        @submit.native.prevent @keyup.enter.prevent>
        <el-form-item label="关键词">
          <el-col :span="8" style="margin-right: 15px;">
            <el-input v-model="filters.comName" clearable placeholder="请输入企业名称" style="margin-left: 1rem;"></el-input>
          </el-col>
          <el-col :span="8" style="margin-left: 15px;">
            <el-input v-model="filters.comNumber" clearable placeholder="请输入企业统一社会信用代码" style=""></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="企业资质">
          <el-col :span="8" style="margin-right: 15px;">
            <el-select v-model.trim="filters.zzName" filterable :clearable="true" placeholder="请输入最多3个资质名称" multiple
              :multiple-limit="3" remote reserve-keyword :remote-method="remoteMethod" :loading="loading"
              style="width: 100%;" 
              @focus="focusZzname"
              @change="changeZzname"
              @visible-change="handleVisibleChange"
              v-click-outside="handleClickOutside"
              ref="zzNameRef">
              <span id="testspan2" >
              <el-option  v-for="item in restaurants" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </span>
            </el-select>
          </el-col>
          <el-col :span="12" style="margin-right: 15px;">
            <el-select ref="endDateIdRef" v-model="filters.endDateId" filterable :clearable="true" placeholder="请选择到期时间"
              >
              <el-option v-for="item in endDateIdoptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="工商相关">
          <el-col :span="8" style="margin-right: 15px;">
            <el-input v-model="filters.comBusinessScope" clearable placeholder="请输入经营范围"
              style="margin-right: 15px;"></el-input>
          </el-col>
          <el-col :span="12">
            <el-select ref="province" filterable clearable v-model="state_region.province" placeholder="注册属地: 省/直辖市"
              @change="provinceChange">
              <el-option v-for="item in region.province" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <template v-if="modelType !== 'talentPerson'">
              <el-select ref="city" v-model="state_region.city" placeholder="市" filterable clearable
                @change="cityChange">
                <el-option v-for="item in region.city" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
            <template v-if="modelType === 'project'">
              <el-select ref="area" v-model="state_region.area" placeholder="区" filterable clearable
                @change="areaChange">
                <el-option v-for="item in region.area" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="更多筛选">
          <div style="display: flex; align-items: center;">
            <div style="display: flex;align-items: center;">
              <el-popover placement="bottom" trigger="click" v-model="popoverVisible1" @show="handlePopoverShow1"
                style="margin: 0 10px;">
                <ul class="custom-select-list">
                  <li v-for="item in isUnlockList" :key="item.index"
                    :class="{ 'selected': filters.isUnlock === item.index }" @click="handleSelectpopover1(item)">
                    {{ item.name }}
                  </li>
                </ul>
                <el-button type="text" slot="reference" class="popover-trigger-btn">
                  <span :style="filters.isUnlock === '-1' ? '' : 'color:#409EFF'">{{ filters.isUnlock | isUnlockFilter }}</span>
                  <i :class="popoverVisible1 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                    :style="filters.isUnlock === '-1' ? '' : 'color: #409EFF'" />
                </el-button>
              </el-popover>

              <el-popover placement="bottom" trigger="click" v-model="popoverVisible2" @show="handlePopoverShow2"
                style="margin: 0 10px;">
                <ul class="custom-select-list">
                  <li v-for="item in lockStatusList" :key="item.index"
                    :class="{ 'selected': filters.comLockStatus === item.index }" @click="handleSelectpopover2(item)">
                    {{ item.name }}
                  </li>
                </ul>
                <el-button type="text" slot="reference" class="popover-trigger-btn">
                  <!-- 解锁状态，锁定状态，联系电话，资质类别 -->
                   <span :style="filters.comLockStatus === '-1' ? '' : 'color:#409EFF'">{{ filters.comLockStatus | lockStatusListFilter }}</span>
                  <i :class="popoverVisible2 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                    :style="filters.comLockStatus === '-1' ? '' : 'color: #409EFF'" />
                </el-button>
              </el-popover>

              <el-popover placement="bottom" trigger="click" v-model="popoverVisible3" @show="handlePopoverShow3"
                style="margin: 0 10px;">
                <ul class="custom-select-list">
                  <li v-for="item in isPhoneList" :key="item.index"
                    :class="{ 'selected': filters.isNeedPhone === item.index }" @click="handleSelectpopover3(item)">
                    {{ item.name }}
                  </li>
                </ul>
                <el-button type="text" slot="reference" class="popover-trigger-btn">
                  <span :style="filters.isNeedPhone === '-1' ? '' : 'color:#409EFF'">{{ filters.isNeedPhone | isNeedPhoneFilter }}</span>
                  <i :class="popoverVisible3 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                    :style="filters.isNeedPhone === '-1' ? '' : 'color: #409EFF'" />
                </el-button>
              </el-popover>

              <el-popover placement="bottom" trigger="click" v-model="popoverVisible4" @show="handlePopoverShow4"
                style="margin: 0 10px;">
                <ul class="custom-select-list">
                  <li v-for="item in ZzTypesList" :key="item.ZzTypeId"
                    :class="{ 'selected': filters.zzTypeId === item.ZzTypeId }" @click="handleSelectpopover4(item)">
                    {{ item.ZzTypeName }}
                  </li>
                </ul>
                <el-button type="text" slot="reference" class="popover-trigger-btn">
                  <span :style="filters.zzTypeId === '0' ? '' : 'color:#409EFF'">{{ filters.zzTypeId === '0' ? '资质类别' : ZzTypeNamecoyp.ZzTypeName }}</span>
                  <i :class="popoverVisible4 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                    :style="filters.zzTypeId === '0' ? '' : 'color: #409EFF'" />
                </el-button>
              </el-popover>
            </div>
            <div style="margin-left: 50px;">
              <!-- <el-button type="primary" size="mini" @click.native.prevent="searching">搜索</el-button> 过滤器-->
              <el-button type="info" size="mini" @click.native.prevent="refresh">重置</el-button>
            </div>
          </div>
        </el-form-item>
        <!-- <el-form-item label="已选条件">
          <div v-if="choiceList.length">
            <el-tag v-for="item in choiceList" :key="item.key" style="margin-right: 10px;">
            {{ item.Label }}
          </el-tag>
          </div>
          <div v-else style="color: #C0C4CC">暂未选择搜索条件</div>
        </el-form-item> -->
      </el-form>
    </div>
    <div v-if="modelType === 'retrievalNumber'" style=" background-color: #FAFBFD; padding: 0px 15px;">
      <div style="display: flex; align-items: center;justify-content: space-between; flex-wrap: nowrap;">
        <div style="color: #404040; padding: 14px 0;width: 300px;"><span>搜索到<span style="color: #F56C6C">超 {{
          countcount }}
            </span>个企业</span></div>
        <div style="display: flex;align-items: center;">
          <div v-for="(field, index) in searchForm.fields">
            <div v-if="field.type === 'sortType'" style="position: relative; ">
              <div style="width: 60px;">
                <span>{{ field.label }}</span>
                <i @click="tosort('0')" class="el-icon-caret-top"
                  :style="filters[field.name] === '0' ? 'color: #409EFF;' : ''"
                  style="cursor: pointer; position: absolute; left: 30px;top:-5px"></i>
                <i @click="tosort('1')" class="el-icon-caret-bottom"
                  :style="filters[field.name] === '1' ? 'color: #409EFF;' : ''"
                  style="cursor: pointer; position: absolute; left: 30px;top:5px"></i>
              </div>
            </div>
            <div v-else-if="field.type === 'sortWay'">
              <el-radio-group v-model="filters[field.name]" size="small" class="no-border-radio-group">
                <el-radio-button v-for="item in field.options" :label="item.value" class="no-border-radio-button">{{
                  item.label }}</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getComZzTypes, getDistricts, searchZzName, getComCount } from '@/api/company'
export default {
  directives: {
    clickOutside: {
      bind(el, binding, vnode) {
        el.clickOutsideEvent = function(event) {
          if (!(el === event.target || el.contains(event.target))) {
            vnode.context[binding.expression](event);
          }
        };
        document.addEventListener('click', el.clickOutsideEvent);
      },
      unbind(el) {
        document.removeEventListener('click', el.clickOutsideEvent);
      }
    }},
  name: 'RetrievalNumberSearchform',
  components: {},
  props: {
    searchForm: { type: Object, default: null },
    modelType: { type: String, default: null },
  },
  filters:{
    isUnlockFilter(status) {
      const statusMap = {
      '-1': '解锁状态',
      '0': '未解锁' ,
      '1':  '已解锁' 
      }
      return statusMap[status]
    },
    lockStatusListFilter(status) {
      const statusMap = {
      '-1': '锁定状态',
      '0': '未锁定' ,
      '1':  '已锁定' 
      }
      return statusMap[status]
    },
    isNeedPhoneFilter(status) {
      const statusMap = {
      '-1': '联系方式',
      '0': '有联系方式' ,
      '1':  '有手机' 
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      isDropdownVisible: false,
      endDateIdoptions: [
        { value: '0', label: '全部' },
        { value: '1', label: '已经过期' },
        { value: '2', label: '1个月' },
        { value: '3', label: '3个月' },
        { value: '4', label: '半年' },
        { value: '5', label: '1年' }
      ],
      allFilter: '',
      popoverVisible1: false,
      popoverVisible2: false,
      popoverVisible3: false,
      popoverVisible4: false,
      countcount: 0,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 10
      },
      maxPage: 50, // 最多显示多少页数据
      ZzTypesList: [], // 资质列表
      isPhoneList: [
        { index: '-1', name: '全部' },
        { index: '0', name: '有联系方式' },
        { index: '1', name: '有手机' }
      ],
      isUnlockList: [
        { index: '-1', name: '全部' },
        { index: '0', name: '未解锁' },
        { index: '1', name: '已解锁' }
      ],
      lockStatusList: [
        { index: '-1', name: '全部' },
        { index: '0', name: '未锁定' },
        { index: '1', name: '已锁定' }
      ],
      region: {
        province: [],
        city: [],
        area: []
      },
      filters: null,
      state_region: null,
      restaurants: [], //资质名称列表
      iswatch: true,
      choiceList: [],
      zznamecholselist:[],
      ZzTypeNamecoyp:{}
    }
  },
  watch: {
    // 监听对象filters，
    filters: {
      handler(newVal, oldVal) {
        let copyObj = Object.assign({}, newVal);
        // if (newVal.zzName) {
        //   copyObj.zzName = newVal.zzName.join('#');
        // }
        // 同步设置 store
        if (this.iswatch) {
          this.getComCountCount(copyObj)
          this.$emit('searchFormEmit', copyObj)//
          this.setFilters(newVal)
          this.$emit('watchTypeEmit', newVal.type)
        }
        // 所有条件
        this.allFilter = '';//
        this.choiceList = [];
        for (let key in newVal) {
          if ((
            newVal[key] != ''
            && newVal[key] != undefined
            && (newVal[key] != '0' || ['sortType', 'isUnlock', 'comLockStatus', 'isNeedPhone'].indexOf(key) > -1)
            && newVal[key] != '-1'
            // && ['zzTypeId'].indexOf(key) < 0
          )
          ) {
            //转换
            let selectValue = newVal[key];
            let label = selectValue;
            //选项
            let formFilter = this.searchForm.fields.filter(p => p.name == key)[0];
            if (!formFilter) {
              formFilter = {};
            }
            if (['endDateId', 'sortFieldId', 'sortType'].indexOf(key) > -1) {
              label = formFilter.options.filter(p => p.value == selectValue)[0].label;
            } else if (key == 'distId') {
              let province = this.region.province.filter(p => p.value == selectValue);
              if (province && province.length > 0) {
                label = province[0].label;
              } else {
                let city = this.region.city.filter(p => p.value == selectValue);
                if (city && city.length > 0) {
                  label = city[0].label;
                }
              }
            } else if (key == 'isUnlock') {
              formFilter.label = '解锁状态';
              label = this.isUnlockList.filter(p => p.index == selectValue)[0].name;
            } else if (key == 'comLockStatus') {
              formFilter.label = '锁定状态';
              label = this.lockStatusList.filter(p => p.index == selectValue)[0].name;
            }
            else if (key == 'isNeedPhone') {
              formFilter.label = '联系电话';
              label = this.isPhoneList.filter(p => p.index == selectValue)[0].name;
              // label=`${formFilter.label}-${label}`;
            } else if (key == 'zzTypeId') {
              label = this.ZzTypesList.filter(p => p.ZzTypeId == selectValue)[0].ZzTypeName;
            }
            this.choiceList.push({
              Name: formFilter.label,
              Label: label,
              Value: selectValue,
              Key: key,
            });
          }
        }
        // console.log('this.ZzTypesList',this.ZzTypesList);
        // console.log('choiceList',this.choiceList);
      },
      deep: true
    },
    state_region: {
      handler(newVal, oldVal) {
        // 同步设置 store
        this.setRegion(newVal)
      },
      deep: true
    },
    'searchForm.reset': {
      handler(newVal) {
        if (newVal) {
          // 重置条件
          this.refresh()
        }
      },
      deep: true
    }
  },
  created() {
    // 初始化筛选条件
    this.getFilters()
    this.getComZzTypesItems()
    if (this.searchForm.region) {
      this.getRegion()
      this.getDistrictsList()
    }
    this.getComCountCount(this.filters) //要求：1，带上所有的搜索条件。2，只在第一页请求，分页不请求
  },
  mounted(){
    document.addEventListener('click', this.handleOutsideClick) // 可选：监听全局点击事件，手动关闭下拉框。
  },
  methods: {
    handleOutsideClick(event){
      // let selectElement = this.$refs.zzNameRef.$el;
      // if (!selectElement.contains(event.target)) {
      //     this.$refs.zzNameRef.blur(); // 调用 blur 方法关闭下拉框
      //   }
        for (let key in this.$refs) {
        if (true||key.startsWith('child')) { //处理全部, 确保只处理我们关心的refs
          // 执行一些操作，例如调用子组件的方法或访问其数据
          try {
            let selectElement = this.$refs[key].$el;
            if (!selectElement.contains(event.target))
                this.$refs[key].blur()
          } catch (error) {
            console.log('handleOutsideClick-处理异常',error);
          }
          
        }
      }
    },
    handleSelectpopover1(item) {
      this.filters.isUnlock = item.index;
      this.popoverVisible1 = false; // 选择后关闭popover
      // 这里可以添加选择后的其他逻辑
    },
    handleSelectpopover2(item) {
      this.filters.comLockStatus = item.index;
      this.popoverVisible2 = false; // 选择后关闭popover
      // 这里可以添加选择后的其他逻辑
    },
    handleSelectpopover3(item) {
      this.filters.isNeedPhone = item.index;
      this.popoverVisible3 = false; // 选择后关闭popover
      // 这里可以添加选择后的其他逻辑
    },
    handleSelectpopover4(item) {
      this.ZzTypeNamecoyp = item
      if (item.ZzTypeId === '0') {
        this.refresh()
      } else {
        if (this.modelType === 'retrievalNumber') {
          this.filters.zzTypeId = item.ZzTypeId
        } 
      }
      this.popoverVisible4 = false; // 选择后关闭popover
      // 这里可以添加选择后的其他逻辑
    },
    handleClickOutside() {
      if (!this.isDropdownVisible) {
        this.handlezzNameBlur();
      }
    },
    handleVisibleChange(v) {
      this.isDropdownVisible = v;
      if (!v) {
        this.handlezzNameBlur();
      }
    },
    changeZzname(v){
      // 多选下拉框导致blur事件不触发，需要手动关闭
     if(v.length > 0){
      this.$nextTick(() => {
        this.$refs.zzNameRef.visible = false; // 选了就设置失焦，失焦收起下拉框，解决放在crm兼容问题
        })
     }
    },
    handlezzNameBlur() {
      this.$refs.zzNameRef.visible = false; // 点击其他地方失焦后，收起下拉框，解决放在crm兼容问题
    },
    focusZzname(){
      this.remoteMethod('')
    },
    handlePopoverShow1() {
      this.$nextTick(() => {
        this.$refs.selectRef1.focus()
        this.$refs.selectRef1.$el.querySelector('.el-input__inner').click()// 对于 Element UI 2.x，可能需要触发点击事件
      })
    },
    handlePopoverShow2() {
      this.$nextTick(() => {
        this.$refs.selectRef2.focus()
        this.$refs.selectRef2.$el.querySelector('.el-input__inner').click()// 对于 Element UI 2.x，可能需要触发点击事件
      })
    },
    handlePopoverShow3() {
      this.$nextTick(() => {
        this.$refs.selectRef3.focus()
        this.$refs.selectRef3.$el.querySelector('.el-input__inner').click()// 对于 Element UI 2.x，可能需要触发点击事件
      })
    },
    handlePopoverShow4() {
      this.$nextTick(() => {
        this.$refs.selectRef4.focus()
        this.$refs.selectRef4.$el.querySelector('.el-input__inner').click()// 对于 Element UI 2.x，可能需要触发点击事件
      })
    },
    tosort(v) {
      this.filters.sortType = v
      this.$emit('searchFormEmit', this.filters)
    },
    async getComCountCount(v) {
      this.loading = true
      this.listQuery = { ...this.listQuery, ...v }
      getComCount(this.listQuery).then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.countcount = res.data.count
          // 最多展示 this.maxPage 页数据
          this.total = Math.ceil(this.countcount / this.listQuery.pageSize) > this.maxPage ? this.listQuery.pageSize * this.maxPage : this.countcount
          this.$emit('totalEmit', this.total)
        }
      })
    },
    remoteMethod(query) {
      searchZzName({ keyWord: query ? query : '' }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          const options = []
          res.data.ZzNames.forEach((item) => {
            const o = { value: item.ZzName }
            options.push(o)
          })
          this.restaurants = options
        }
      })
    },
    querySearchAsync(queryString, cb) {
      searchZzName({ keyWord: queryString ? queryString : '' }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          const options = []
          res.data.ZzNames.forEach((item) => {
            const o = { value: item.ZzName }
            options.push(o)
          })
          this.restaurants = options
          cb(this.restaurants)
        }
      })
    },
    // removeTag(tag) {
    //   console.log('old-filters', this.filters, tag)
    //   this.choiceList = this.choiceList.filter(p => p.key != tag.Key);
    //   if (false) {

    //   } else {
    //     this.filters[tag.Key] = ''
    //   }
    //   console.log('new-filters', this.filters, tag)
    // },
    getFilters() {
      this.filters = this.$store.getters[this.modelType + '/getFilters']
    },
    setFilters(filters) {
      this.$store.dispatch(this.modelType + '/setFilters', filters)
    },
    resetFilters() {
      this.$store.dispatch(this.modelType + '/resetFilters')
      // 重置后重新获取
      this.getFilters()
    },
    getRegion() {
      this.state_region = this.$store.getters[this.modelType + '/getRegion']
      // 初始化地址
      if (this.state_region) {
        if (this.state_region.province !== '') {
          this.getDistrictsList(this.state_region.province, 'city')
        }

        if (this.state_region.city !== '') {
          this.getDistrictsList(this.state_region.city, 'area')
        }
      }
    },
    setRegion(filters) {
      this.$store.dispatch(this.modelType + '/setRegion', filters)
    },
    resetRegion() {
      this.$store.dispatch(this.modelType + '/resetRegion')
      this.region.city = []
      this.region.area = []
      // 重置后重新获取
      this.getRegion()
    },
    provinceChange(value) {
      if (this.modelType !== 'talentPerson') {
        this.getDistrictsList(value, 'city')
        this.region.city = []
        this.region.area = []
      }
      this.filters.distId = value
    },
    cityChange(value) {
      if (this.modelType === 'project') {
        this.getDistrictsList(value, 'area')
        this.region.area = []
      }

      this.filters.distId = value
    },
    areaChange(value) {
      this.filters.distId = value
    },
    getDistrictsList(distId = 0, node = 'province') {
      this.loading = true
      getDistricts({ distId: distId }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          const options = []
          res.data.dists.forEach((item) => {
            const o = { value: item.DistId, label: item.DistName }
            options.push(o)
          })
          this.region[node] = options
        }
      })
    },
    getComZzTypesItems() {
      this.loading = true
      if (this.modelType === 'retrievalNumber') {
        getComZzTypes().then((res) => {
          this.loading = false
          if (res.code === 200) {
            const arr = { ZzTypeId: '0', ZzTypeName: '全部' }
            res.data.ZzTypes.forEach((item) => {
              item.ZzTypeId = item.ZzTypeId + ''
            })
            this.ZzTypesList = res.data.ZzTypes
            this.ZzTypesList.unshift(arr)
          }
        })
      }
    },
    handleClick(tab) {
      if (tab === '0') {
        this.refresh()
      } else {
        if (this.modelType === 'retrievalNumber') {
          this.filters.zzTypeId = tab
        } else if (this.modelType === 'project' || this.modelType === 'water') {
          this.filters.projectTypeName = tab
        }
      }
    },
    refresh() {
      // 重置条件
      this.resetFilters()
      this.resetRegion()

      // 恢复重置条件
      this.searchForm.reset = false
    },
  }
}
</script>
<style scoped>
::v-deep .el-form-item{
  margin-bottom: 15px !important;
}
/* ul,li的样式 */
/* 自定义列表样式 */
.custom-select-list {
  list-style: none;
  margin: 0;
  padding: 5px 0;
  min-width: 120px;
}

.custom-select-list li {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.custom-select-list li:hover {
  background-color: #f5f7fa;
}

.custom-select-list li.selected {
  color: #409EFF;
  font-weight: 500;
  background-color: #ecf5ff;
}

/* 触发按钮样式 */
.popover-trigger-btn {
  color: #606266;
  font-weight: 700;
  padding: 0;
}

/* 调整popover样式 */
.custom-list-popover {
  padding: 0;
}

/* 结束ul>li */
::v-deep .no-border-radio-group .el-radio-button__inner {
  border: none !important;
  background-color: rgb(250, 251, 253) !important;
}

::v-deep .no-border-radio-group .el-radio-button__orig-radio:checked+.el-radio-button__inner {
  background-color: rgb(250, 251, 253) !important;
  box-shadow: -1px 0 0 0 #eee;
  color: #409EFF;
}
</style>
